package com.feonix.common.service;

import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.feonix.common.basedao.Query;
import com.feonix.common.dao.GridViewDAO;
import com.feonix.common.util.MathUtil;
import com.feonix.common.view.grid.GridRow;
import com.feonix.common.view.grid.GridView;
import com.feonix.common.view.grid.GridViewDelegate;
import com.feonix.common.view.grid.GridViewSql;

/**
 * @CopyRight (c)1993-2017
 * @Project m-complat-common
 * @Comments 列表页视图业务类
 * @NameSpace com.feonix.common.service
 * @Author Feonixzw
 * @CreateDate 2017年12月6日
 */
@Service
public class GridViewService {
	private final Log logger = LogFactory.getLog(super.getClass());

	@Autowired
	private GridViewDAO gridViewDAO;

	public void find(GridViewSql gridViewSql) {
		String countSql = gridViewSql.getCountSql();
		GridView gridView = gridViewSql.getGridView();
		GridViewDelegate gridViewDelegate = gridView.getDelegate();
		if (gridViewDelegate == null) {
			logger.error("gridview delegate is null");
			return;
		}
		Query query = gridViewDAO.createQuery(countSql);
		query.setSafeCheck(gridViewSql.isSafeCheck());
		query.addParameters(gridViewSql.getParamMap());
		//获取总记录数
		Integer total = gridViewDAO.queryForInteger(query);
		if ((total != null) && (total.intValue() > 0)) {
			//获取总页数
			int pageNum = MathUtil.ceil(total.doubleValue() / gridView.getPageSize());
			if ((pageNum > 0) && (pageNum < gridView.getPageNumber())) {
				gridView.setPageNumber(pageNum);
			}
			gridView.setTotal(total.intValue());
			String selectSql = gridViewSql.getSelectSql();
			query = gridViewDAO.createQuery(selectSql).addParameters(gridViewSql.getParamMap())
					.setPageNo(Integer.valueOf(gridView.getPageNumber()))
					.setPageSize(Integer.valueOf(gridView.getPageSize()));
			List<Map<String, Object>> resultList = gridViewDAO.queryForList(query);
			GridRow gridRow = null;
			int index = 0;
			for (Map<String, Object> map : resultList) {
				gridRow = new GridRow();
				gridRow.setIndex(Integer.valueOf(index));
				gridRow.setGridView(gridViewSql.getGridView());
				gridRow.setModelMap(gridViewSql.getGridView().getModelMap());
				gridViewDelegate.createRow(gridRow, map, Integer.valueOf(index));
				gridView.addRow(gridRow);
				++index;
			}
		}
	}
}
